package com.wfuhui.book.ui.mine;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wfuhui.book.R;
import com.wfuhui.book.model.Member;
import com.wfuhui.book.ui.login.LoginActivity;
import com.wfuhui.book.util.Constant;
import com.wfuhui.book.util.GlideImageLoader;
import com.wfuhui.book.util.PreferencesService;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 押金
 */
public class DepositActivity extends AppCompatActivity {

    private Member user = new Member();

    private Button payBtn, refundBtn;

    private TextView titleTv, contentTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deposit);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        payBtn = findViewById(R.id.pay);
        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user.getDeposit().compareTo(new BigDecimal(0)) > 0){

                }else{
                    Intent intent = new Intent(DepositActivity.this, DepositPayActivity.class);
                    startActivity(intent);
                }
            }
        });
        titleTv = findViewById(R.id.title);
        contentTv = findViewById(R.id.content);

        payBtn = findViewById(R.id.pay);
        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DepositActivity.this, DepositPayActivity.class);
                startActivity(intent);
                finish();
            }
        });
        refundBtn = findViewById(R.id.refund);
        refundBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refund();
            }
        });
        this.getMember();
    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 1:
                    if(user.getDeposit().compareTo(new BigDecimal(0)) > 0){ //存在押金
                        titleTv.setText("您已缴纳押金" + user.getDeposit() + "元");
                        contentTv.setText("可借阅图书");
                        payBtn.setVisibility(View.GONE);
                        refundBtn.setVisibility(View.VISIBLE);
                    }else{
                        titleTv.setText("您还未缴纳押金");
                        contentTv.setText("缴纳押金后可借阅图书");
                        payBtn.setVisibility(View.VISIBLE);
                        refundBtn.setVisibility(View.GONE);
                    }
                    break;
                case 2:
                    String info = "您已退款成功";
                    Toast.makeText(DepositActivity.this, info, Toast.LENGTH_SHORT).show();
                    finish();
                    break;

            }
        }
    };

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        //返回按钮点击事件
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void getMember(){
        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        if(token == null || "".equals(token)){
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/member/info")
                .addHeader("token", token)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/member/info", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/member/info", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if(code == 0){

                        JSONObject memberJson = json.getJSONObject("member");
                        user = new Member();
                        user.setId(memberJson.getInt("id"));
                        user.setNickname(memberJson.getString("nickname"));
                        user.setRealName(memberJson.getString("realName"));
                        user.setMobile(memberJson.getString("mobile"));
                        user.setAvatarUrl(memberJson.getString("avatarUrl"));
                        user.setDeposit(new BigDecimal(memberJson.getDouble("deposit")));
                        handler.sendEmptyMessage(1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    /**
     * 退款
     */
    private void refund(){
        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        if(token == null || "".equals(token)){
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/member/delDeposit")
                .addHeader("token", token)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/member/delDeposit", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/member/delDeposit", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if(code == 0){
                        handler.sendEmptyMessage(2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }
}
